package com.party.admin.biz.wechat;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.party.admin.web.dto.input.wechat.GetTicketResponse;
import com.party.common.constant.WechatConstant;
import com.party.common.utils.StringUtils;
import com.party.common.utils.refund.WechatPayUtils;
import com.party.common.utils.wechat.WechatUtils;
import com.party.core.model.wechatPlatform.WechatOpenMember;
import com.party.core.service.wechatPlatform.IWechatOpenMemberService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

/**
 * 微信服务接口
 * Created by wei.li
 *
 * @date 2017/5/19 0019
 * @time 11:31
 */
@Service
public class WechatBizService {

    //微信接口凭证
    public static final String ACCESS_TOKEN = "ACCESS_TOKEN";

    @Autowired
    private IWechatOpenMemberService wechatOpenMemberService;

    // 是否需要刷新小程序token
    @Value("#{wechat['wechat.xcx.refreshToken']}")
    private String refreshToken;

    protected static Logger logger = LoggerFactory.getLogger(WechatBizService.class);

    /**
     * 获取微信 jsapi ticket
     *
     * @param accessToken 接口交互令牌
     * @return 交互数据
     */
    public GetTicketResponse getTicket(String accessToken) throws Exception {
        String url = WechatConstant.GET_TICKET_URL.replace(ACCESS_TOKEN, accessToken);
        logger.info("获取 js api ticket 请求报文{}", url);
        JSONObject response = WechatUtils.httpRequest(url, WechatUtils.GET, null);

        logger.info("获取微信 js api ticket 响应报文{}", response);
        GetTicketResponse ticketResponse = JSONObject.toJavaObject(response, GetTicketResponse.class);
        if (StringUtils.isEmpty(ticketResponse.getTicket())) {
            throw new Exception("刷新ticket异常：" + JSONObject.toJSONString(response));
        }
        return ticketResponse;
    }

    /**
     * 微信长连接转短连接
     *
     * @param longUrl     长连接
     * @param accessToken 交互令牌
     * @return 返回连接
     */
    public String longToShort(String longUrl, String accessToken) {
        String url = WechatConstant.LONG_TO_SHORT_URL.replace(ACCESS_TOKEN, accessToken);
        Map<String, Object> requestMap = Maps.newHashMap();
        requestMap.put("access_token", accessToken);
        requestMap.put("action", "long2short");
        requestMap.put("long_url", longUrl);
        String requestData = JSONObject.toJSONString(requestMap);
        logger.info("微信长连接转短链接请求报文{}", requestData);
        String responseData = WechatPayUtils.httpsPost(url, requestData);
        logger.info("微信长连接转短连接响应报文{}", responseData);

        if (StringUtils.isNotEmpty(responseData)) {
            Map<String, String> responseMap = JSONObject.parseObject(responseData, Map.class);
            return responseMap.get("short_url");
        }
        return null;
    }

    /**
     * 长连接转短连接
     *
     * @param longUrl 长连接
     * @param publisher 发布者
     * @return 短连接
     */
    public String longToShort2(String longUrl, String publisher) {
        String token = null;
        if (StringUtils.isNotEmpty(publisher)) {

            // 如果发布者绑定了自己的商户，就使用自己的token，否则就使用系统的token
            WechatOpenMember wechatOpenMember = wechatOpenMemberService.findByMemberId(publisher);
            if (null != wechatOpenMember) {
                token = wechatOpenMember.getAuthorizerAccessToken();
            }
            if (StringUtils.isEmpty(token)) {
                wechatOpenMember = wechatOpenMemberService.getSystem();
                token = wechatOpenMember.getAuthorizerAccessToken();
            }
        } else {
            WechatOpenMember wechatOpenMember = wechatOpenMemberService.getSystem();
            token = wechatOpenMember.getAuthorizerAccessToken();
        }
        return longToShort(longUrl, token);
    }

    public boolean refreshToken(String type) {
        if (StringUtils.isNotEmpty(type) && type.indexOf("XCX") != -1) {
            if (refreshToken.equals("true")) {
                return true;
            } else {
                return false;
            }
        }
        return true;
    }

    public void generateQrCode() {
        WechatOpenMember wechatOpenMember = wechatOpenMemberService.getSystem();
        String token = wechatOpenMember.getAuthorizerAccessToken();
        String createRequestUrl = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + token;

        Map<String, Object> params = Maps.newHashMap();
        params.put("action_name", "QR_LIMIT_STR_SCENE");

        Map<String, Object> sceneMap = Maps.newHashMap();


        Map<String, Object> sceneStrMap = Maps.newHashMap();
        sceneStrMap.put("scene_str", "扫描二维码 营销");

        sceneMap.put("scene", sceneStrMap);

        params.put("action_info", sceneMap);


        String requestData = JSONObject.toJSONString(params);
        logger.info("创建带参数的二维码，请求参数：{}", requestData);
        String responseData = WechatPayUtils.httpsPost(createRequestUrl, requestData);
        logger.info("创建带参数的二维码，响应结果：{}", responseData);

        if (responseData.indexOf("ticket") != -1) {
            JSONObject jsonObject = JSONObject.parseObject(responseData);

            String ticket = jsonObject.get("ticket").toString();
            String url = jsonObject.getString("url").toString();

            try {
                String encodeTicket = URLEncoder.encode(ticket, "UTF-8");
                String showRequestUrl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + encodeTicket;
                System.out.println(showRequestUrl);
                System.out.println("url" + url);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    }
}
